<?php


namespace App\Http\Controllers;


use Elasticsearch\ClientBuilder;
use Illuminate\Http\Request;
use NunoMaduro\Collision\Highlighter;

class ElasticSearch extends Controller
{
    private $esClient;//实例变量
    private $indexName;
    //
    public function __construct()
    {
        $this->esClient = ClientBuilder::create()->setHosts(config("esconfig"))->build();//es初始化
        $this->indexName = "cmc";
    }
    public function createIndex() {
        // 创建索引
        $params = [
            // 生成索引的名称
            'index' => $this->indexName,
            // 类型 body
            'body' => [
                'settings' => [
                    // 分区数
                    'number_of_shards' => 5,
                    // 副本数
                    'number_of_replicas' => 1
                ],
                'mappings' => [
                    // 字段  类似表字段，设置类型
                    'properties' => [
                        'title' => [
                            'type' => 'text',
                            'analyzer' => 'ik_max_word',
                            'search_analyzer' => 'ik_max_word'
                        ],
                        'content' => [
                            'type' => 'text',
                            // 中文分词  张三你好   张三  你好 张三你好
                            'analyzer' => 'ik_max_word',
                            'search_analyzer' => 'ik_max_word'
                        ]
                    ]

                ]
            ]
        ];
        // 创建索引
        $response = $this->esClient->indices()->create($params);
        return $response;
    }

    public function save(Request $request) {

        $name = $request->input("name");
        $desc = $request->input("desc");
        $id = $request->input("id");

        $params = [
            'index' => $this->indexName,
            'type' => '_doc',
            'id' => $id,
            'body' => [
                'name' => $name,
                'desc' => $desc,
            ],
        ];
        // 添加数据到索引文档中
        $this->esClient->index($params);
    }
    public function search(Request $request)
    {
        $searchKey = $request->input('searchkey');
        $response = [];
        if ($searchKey) {
            $params = [
                'index' => $this->indexName,

                'body' => [
                    '_source' => true,
                    'query' => [
                        'multi_match' => [
                            'query' => $searchKey,
                            "fields" => ["name", "desc"]
                        ]
                    ],
                    'highlight' => array(
                        'fields' => array(
                            'name' => new Highlighter(),
                            'desc' => new Highlighter()
                        )
                    )
                ]
            ];

            $response = $this->esClient->search($params);

            $tmp = $tmpResult = [];
            if ($response['hits']['total']['value'] > 0) {
                foreach ($response['hits']['hits'] as $res) {

                    $tmp["_id"] = $res["_id"];
                    $tmp["_source"] = $res["_source"];
                    $tmp["name"] = isset($res["highlight"]["name"][0]) ? $res["highlight"]["name"][0] : '';
                    $tmp["desc"] = $res["highlight"]["desc"][0];
                    $tmpResult[] = $tmp;
                }
            }
        }
        return json_encode(["code" => "200", "message" => "成功", 'data' => $tmpResult]);
    }
}